/**
 * 工作项相关的自定义 Hook
 */

import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import { pingCodeAPI } from '../utils/pingcodeApi';
import type {
  WorkItem,
  Project,
  WorkItemType,
  WorkItemState,
  WorkItemPriority,
  User,
  WorkItemQueryParams,
} from '../types/workItem';

export function useWorkItems(initialParams?: WorkItemQueryParams) {
  const [workItems, setWorkItems] = useState<WorkItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState<string | null>(null);

  const fetchWorkItems = useCallback(async (params?: WorkItemQueryParams) => {
    console.log('开始获取工作项:', params);
    setLoading(true);
    setError(null);

    try {
      const response = await pingCodeAPI.getWorkItems(params);
      console.log('获取工作项成功:', response);
      setWorkItems(response.values || []);
      setTotal(response.total || 0);

      // 如果有提示信息，显示给用户
      if (response.message) {
        message.warning(response.message);
      } else if (response.values && response.values.length === 0 && response.total === 0) {
        message.info('暂无工作项数据，请尝试调整查询条件');
      }
    } catch (err) {
      console.error('获取工作项失败:', err);
      const errorMessage = err instanceof Error ? err.message : '获取工作项失败';
      setError(errorMessage);
      message.error(errorMessage);
      // 出错时重置数据
      setWorkItems([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (initialParams) {
      fetchWorkItems(initialParams);
    }
  }, [fetchWorkItems, initialParams]);

  return {
    workItems,
    loading,
    total,
    error,
    fetchWorkItems,
    refetch: () => fetchWorkItems(initialParams),
  };
}

export function useProjects() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchProjects = useCallback(async () => {
    console.log('开始获取项目列表');
    setLoading(true);
    setError(null);

    try {
      const response = await pingCodeAPI.getProjects({ page_size: 100 });
      console.log('获取项目列表成功:', response);
      setProjects(response.values || []);
    } catch (err) {
      console.error('获取项目列表失败:', err);
      const errorMessage = err instanceof Error ? err.message : '获取项目列表失败';
      setError(errorMessage);
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchProjects();
  }, [fetchProjects]);

  return {
    projects,
    loading,
    error,
    refetch: fetchProjects,
  };
}

export function useWorkItemMeta(projectId?: string) {
  const [types, setTypes] = useState<WorkItemType[]>([]);
  const [states, setStates] = useState<WorkItemState[]>([]);
  const [priorities, setPriorities] = useState<WorkItemPriority[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchAllUsers = useCallback(async (projectId?: string) => {
    const allUsers: User[] = [];

    try {
      if (projectId) {
        // 如果有项目ID，优先获取项目成员
        console.log(`获取项目 ${projectId} 的成员`);
        let pageIndex = 1;
        const pageSize = 100;

        while (true) {
          const response = await pingCodeAPI.getProjectMembers(projectId, {
            page_size: pageSize,
            page_index: pageIndex
          });

          if (response.values && response.values.length > 0) {
            // 提取用户信息，过滤掉团队类型的成员
            const users = response.values
              .filter(member => member.type === 'user' && member.user)
              .map(member => member.user!)
              .filter(user => user); // 确保用户对象存在

            allUsers.push(...users);

            // 如果当前页的数据少于页面大小，说明已经是最后一页
            if (response.values.length < pageSize) {
              break;
            }

            pageIndex++;
          } else {
            break;
          }
        }

        console.log(`获取到项目成员 ${allUsers.length} 个用户`);
      }

      // 如果没有项目ID或者项目成员为空，则获取全局用户列表
      if (!projectId || allUsers.length === 0) {
        console.log('获取全局用户列表');
        let pageIndex = 1;
        const pageSize = 100;

        while (true) {
          const response = await pingCodeAPI.getUsers({
            page_size: pageSize,
            page_index: pageIndex
          });

          if (response.values && response.values.length > 0) {
            allUsers.push(...response.values);

            // 如果当前页的数据少于页面大小，说明已经是最后一页
            if (response.values.length < pageSize) {
              break;
            }

            pageIndex++;
          } else {
            break;
          }
        }

        console.log(`获取到全局用户 ${allUsers.length} 个用户`);
      }

      // 去重，以用户ID为准
      const uniqueUsers = allUsers.reduce((acc, user) => {
        if (!acc.find(u => u.id === user.id)) {
          acc.push(user);
        }
        return acc;
      }, [] as User[]);

      console.log(`去重后共 ${uniqueUsers.length} 个用户`);
      console.log('用户列表详情:', uniqueUsers.map(user => ({
        id: user.id,
        name: user.name,
        display_name: user.display_name
      })));

      // 特别检查是否包含"张潇丫"用户
      const zhangXiaoYaUsers = uniqueUsers.filter(user =>
        user.name?.includes('张潇丫') || user.display_name?.includes('张潇丫')
      );
      if (zhangXiaoYaUsers.length > 0) {
        console.log('找到张潇丫用户:', zhangXiaoYaUsers);
      } else {
        console.log('未找到张潇丫用户');

        // 搜索包含"张"的用户
        const zhangUsers = uniqueUsers.filter(user =>
          user.name?.includes('张') || user.display_name?.includes('张')
        );
        if (zhangUsers.length > 0) {
          console.log('找到包含"张"的用户:', zhangUsers);
        }

        // 搜索包含"潇"或"丫"的用户
        const xiaoYaUsers = uniqueUsers.filter(user =>
          user.name?.includes('潇') || user.display_name?.includes('潇') ||
          user.name?.includes('丫') || user.display_name?.includes('丫')
        );
        if (xiaoYaUsers.length > 0) {
          console.log('找到包含"潇"或"丫"的用户:', xiaoYaUsers);
        }
      }

      return uniqueUsers;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      return [];
    }
  }, []);

  const fetchMeta = useCallback(async () => {
    setLoading(true);

    try {
      const [typesData, statesData, prioritiesData, usersData] = await Promise.allSettled([
        pingCodeAPI.getWorkItemTypes(projectId),
        pingCodeAPI.getWorkItemStates(projectId),
        pingCodeAPI.getWorkItemPriorities(projectId),
        fetchAllUsers(projectId),
      ]);

      if (typesData.status === 'fulfilled') {
        setTypes(typesData.value);
      }

      if (statesData.status === 'fulfilled') {
        setStates(statesData.value);
      }

      if (prioritiesData.status === 'fulfilled') {
        setPriorities(prioritiesData.value);
      }

      if (usersData.status === 'fulfilled') {
        setUsers(usersData.value);
      }
    } catch (err) {
      console.error('获取工作项元数据失败:', err);
    } finally {
      setLoading(false);
    }
  }, [projectId, fetchAllUsers]);

  useEffect(() => {
    fetchMeta();
  }, [fetchMeta]);

  return {
    types,
    states,
    priorities,
    users,
    loading,
    refetch: fetchMeta,
  };
}

export function useWorkItem(workItemId?: string) {
  const [workItem, setWorkItem] = useState<WorkItem | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchWorkItem = useCallback(async (id: string) => {
    setLoading(true);
    setError(null);

    try {
      const item = await pingCodeAPI.getWorkItem(id);
      setWorkItem(item);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取工作项详情失败';
      setError(errorMessage);
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (workItemId) {
      fetchWorkItem(workItemId);
    }
  }, [workItemId, fetchWorkItem]);

  const updateWorkItem = useCallback(async (id: string, data: Partial<WorkItem>) => {
    setLoading(true);
    try {
      const updatedItem = await pingCodeAPI.updateWorkItem(id, data);
      setWorkItem(updatedItem);
      message.success('工作项更新成功');
      return updatedItem;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '更新工作项失败';
      message.error(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    workItem,
    loading,
    error,
    fetchWorkItem,
    updateWorkItem,
    refetch: () => workItemId && fetchWorkItem(workItemId),
  };
}